//
//  MuseekdController.m
//  SolarSimple
//
//  Created by Marcelo Alves on 13/10/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "MuseekdController.h"


@implementation MuseekdController
@synthesize maxFilesPerSearch;
@synthesize maxPeersPerSearch;

- (id) init{
  self = [super init];
  if (self != nil) {
    maxFilesPerSearch = 1000; // TODO: Move to a preference
    maxPeersPerSearch = 100;
  }
  return self;
}


-(void) connect:(id) unused {
  NSLog(@"Connecting to museekd...");
  connection = [[SolarSeekConnection alloc] init];
  [connection start];
}

-(void) shareDownloadFolder {
  NSTask *muscan;
  muscan = [[NSTask alloc] init];
  NSString *basePath = [[NSBundle mainBundle] bundlePath];
  NSString *muscanPath = [NSString stringWithFormat:@"%@/Contents/MacOS/muscan", basePath];
  [muscan setLaunchPath:muscanPath];
  
  NSArray *muscanParameters = [NSArray arrayWithObjects:@"-c", [@"~/Library/Application Support/SolarSeek/1.0/config.xml" stringByExpandingTildeInPath], @"-s", [@"~/Downloads/SolarSeek/Uploads" stringByExpandingTildeInPath], @"-r", @"-v", nil];
  
  [muscan setArguments:muscanParameters];
  [muscan launch];
  
}

-(void) startMuseekd {
  
  [self shareDownloadFolder];
  
  if (museekd) [self stopMuseekd];
  
  museekd = [[NSTask alloc] init];
  NSString *basePath = [[NSBundle mainBundle] bundlePath];
  NSString *museekdPath = [NSString stringWithFormat:@"%@/Contents/MacOS/museekd", basePath];
  [museekd setLaunchPath:museekdPath];
  
  [museekd setStandardOutput:[NSFileHandle fileHandleWithNullDevice]];// point output to /dev/null
  [museekd setStandardError:[NSFileHandle fileHandleWithNullDevice]];// point output to /dev/null
      
  NSArray *museekdParameters = [NSArray arrayWithObjects:@"-c", [@"~/Library/Application Support/SolarSeek/1.0/config.xml" stringByExpandingTildeInPath], nil];
  
  [museekd setArguments:museekdParameters];
  [museekd launch];
  
  [self performSelector:@selector(connect:) withObject:nil afterDelay:3.0];
}

-(void) stopMuseekd {
  [museekd interrupt];
  museekd = nil;
}

-(void) search:(NSString *)term {
  [connection search:term];
}

-(void) downloadFile:(Result *)file {
  [connection downloadFile:file];
}


-(void) dealloc {
  [self stopMuseekd];
  [super dealloc];
}
@end
